/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.smarttmt.idu.web.utilities;

import java.io.BufferedReader;
import java.io.FileReader;
import javax.annotation.Resource;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.servlet.ServletContext;

/**
 *
 * @author Nicolás Rubén Caballero Ortega (helaman58@gmail.com)
 */
@Named(value = "sendEmail")
@ApplicationScoped
public class SendEmail {

    @Resource(name = "mail/smarttmtiduappmail")
    private Session session;

    public SendEmail() {
    }

    /**
     *
     * @param key
     * @param fileName
     * @param titleMessage
     * @param toWho
     * @throws Exception
     */
    public void sendMessage(String key, String fileName, String titleMessage, String toWho) throws Exception {
        //InitialContext ctx = new InitialContext();
        //Session session
        //      = (Session) ctx.lookup("mail/smarttmtiduappmail");
        // Or by injection.  
        //@Resource(name = "mail/<name>")  
        //private Session session;  

        // Create email and headers.  
        Message msg = new MimeMessage(getSession());
        msg.setSubject(titleMessage);
        msg.setRecipient(RecipientType.TO,
                new InternetAddress(
                        toWho,
                        toWho));
        //msg.setRecipient(RecipientType.CC,
        //      new InternetAddress(
        //            "helaman58@gmail.com",
        //          "Nicolas PERSONAL"));
        msg.setFrom(new InternetAddress(
                "sistemaiduvalorizacion@gmail.com",
                "Nuevo Sistema Valorización IDU"));

        // Body text.  
        //BodyPart messageBodyPart = new MimeBodyPart();
        //messageBodyPart.setText("Here are the files.");
        // Multipart message.  
        //Multipart multipart = new MimeMultipart();
        //multipart.addBodyPart(messageBodyPart);
        ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance()
                .getExternalContext().getContext();
        System.out.println(ctx.getRealPath("/")+"WEB-INF/includes/emailTemplates/"+fileName+".html");
        
        BufferedReader br = new BufferedReader(new FileReader(ctx.getRealPath("/")+"WEB-INF/includes/emailTemplates/"+fileName+".html"));
        StringBuilder sb;
        try {
            sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append('\n');
                line = br.readLine();
            }
            String everything = sb.toString();
            System.out.println(everything);
        } finally {
            br.close();
        }
        // Attachment file from string.  
        //messageBodyPart = new MimeBodyPart();
        //messageBodyPart.setFileName("README1.txt");
        //messageBodyPart.setContent(new String(
        //        "file 1 content"),
        //        "text/plain");
        //multipart.addBodyPart(messageBodyPart);

        // Attachment file from file.  
        //messageBodyPart = new MimeBodyPart();
        //messageBodyPart.setFileName("README2.txt");
        //DataSource src = new FileDataSource("file.txt");
        //messageBodyPart.setDataHandler(new DataHandler(src));
        //multipart.addBodyPart(messageBodyPart);
        // Attachment file from byte array.  
        //messageBodyPart = new MimeBodyPart();
        //messageBodyPart.setFileName("README3.txt");
        //src = new ByteArrayDataSource(
        //        "file 3 content".getBytes(),
        //        "text/plain");
        //messageBodyPart.setDataHandler(new DataHandler(src));
        //multipart.addBodyPart(messageBodyPart);
        // Add multipart message to email.  
        //msg.setContent(multipart);
        String aux = sb.toString();
        aux = aux.replace("XzUyM", key);
        System.out.println("********************************************************************************");
        System.out.println(aux);
        msg.setContent(aux, "text/html; charset=utf-8");

        // Send email.  
        Transport.send(msg);
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }
}
